package com._54programer.demo.ws;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description 用于检测channel的心跳的handler
 */
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            switch (event.state()){
                case READER_IDLE:
                    //读空闲
                    System.out.println("读空闲被触发");
                    break;
                case WRITER_IDLE:
                    //写空闲
                    System.out.println("写空闲被触发");
                    break;
                case ALL_IDLE:
                    //读写空闲被触发, 关闭channel
                    System.out.println("读写空闲被触发");
                    System.out.println("触发前: "+WsServerHandler.clients.size());
                    Channel channel = ctx.channel();
                    channel.close();
                    System.out.println("触发后: "+WsServerHandler.clients.size());
                    break;
            }
        }
    }
}